<script setup lang="ts">
import {nextTick, onMounted, onUnmounted, ref, watch} from 'vue'
import MedicineAPI, {MedicineData, MedicineSearchData} from '@/api/medicine'
import {SelectMedicineBasicProps} from '@/component/select-medicine/types.ts';
import {ElMessage, type TableInstance} from 'element-plus';

const props = defineProps<SelectMedicineBasicProps>()

const dataList = ref<MedicineData[]>([])
const loading = ref<boolean>(false)
const current = ref<number>(1)
const size = ref<number>(20)
const totalCount = ref<number>(0)
const filter = ref<Partial<MedicineSearchData>>({})
const timeout = ref()
const tableRef = ref<TableInstance>()
const highlightCurrentIndex = ref<number>(0)
const $emit = defineEmits(['callback'])

const findDataList = () => {
  if (!loading.value) {
    MedicineAPI.findPage(filter.value, current.value, size.value)
        .then((data) => {
          dataList.value = data.records
          totalCount.value = data.total
          loading.value = false
          if (dataList.value && dataList.value.length > 0) {
            nextTick(() => {
              tableRef.value?.setCurrentRow(dataList.value[highlightCurrentIndex.value])
            })
          }
        })
        .catch((err) => {
          console.error(err)
          ElMessage.error('获取分页数据错误')
          loading.value = false
        })
  }
}
onMounted(() => {
  highlightCurrentIndex.value = 0
  findDataList()

  window.addEventListener('keydown', handleKeyDown)
})
onUnmounted(() => {
  window.removeEventListener('keydown', handleKeyDown)
})
watch(
    () => props.value,
    (val) => {
      filter.value = {
        [props.prop]: val
      }

      // 避免频繁请求，设置延迟执行
      if (timeout.value) clearTimeout(timeout.value)
      timeout.value = setTimeout(() => {
        handleSearch()
      }, 1000)
    },
    {immediate: true}
)
const handleSearch = () => {
  highlightCurrentIndex.value = 0
}
const handleCurrentChange = (val: number) => {
  current.value = val
  findDataList()
}
const handleSizeChange = (val: number) => {
  current.value = 1
  size.value = val
  findDataList()
}
const handleKeyDown = (event: any) => {
  if (dataList.value && dataList.value.length > 0) {
    const key = event.key
    debugger
    console.log(key)
    if (key === 'ArrowUp' && highlightCurrentIndex.value > 0) { // 上键盘
      highlightCurrentIndex.value--
      tableRef.value?.setCurrentRow(dataList.value[highlightCurrentIndex.value])
      nextTick(() => {
        scrollToHighlightRow()
      })
    } else if (key === 'ArrowDown' && (highlightCurrentIndex.value !== (dataList.value.length - 1))) {
      highlightCurrentIndex.value++
      tableRef.value?.setCurrentRow(dataList.value[highlightCurrentIndex.value])
      nextTick(() => {
        scrollToHighlightRow()
      })
    } else if (key === 'Enter') {
      handleSelection(dataList.value[highlightCurrentIndex.value])
    }
  }
}
const scrollToHighlightRow = () => {
  if (!tableRef.value) return

  // 1. 获取 el-table 的 body-wrapper（滚动容器）
  const bodyWrapper = tableRef.value.$el.querySelector('.el-table__body-wrapper')
  if (!bodyWrapper) return
  // 2. 找到高亮行的 DOM 节点
  const highlightRow = tableRef.value.$el.querySelector(`.current-row`)
  if (!highlightRow) return
  // 3. 计算目标行的位置并滚动
  const rowTop = highlightRow.offsetTop; // 行距离顶部的距离
  const rowHeight = highlightRow.clientHeight; // 行的高度
  const wrapperHeight = bodyWrapper.clientHeight; // 滚动容器的高度
  // 4. 使目标行居中显示（可选）
  tableRef.value.scrollTo({
    top: rowTop - (wrapperHeight / 2) + (rowHeight / 2)
  })
}

const handleSelection = (row: MedicineData) => {
  $emit('callback', row)
}

defineExpose({
  handleSearch
})
</script>

<template>
  <div class="select-medicine-basic">
    <el-form>
      <el-row style="display: flex">
        <el-col :span="4">
          <el-form-item :label="props.label">
            <el-input v-model="filter[props.prop]" @change="handleSearch"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-table
        ref="tableRef"
        class="select-medicine-basic_table"
        :data="dataList"
        border
        show-overflow-tooltip
        max-height="500"
        row-key="id"
        highlight-current-row
        @cell-dblclick="handleSelection"
    >
      <el-table-column label="代码" prop="code" min-width="80" align="center" show-overflow-tooltip/>
      <el-table-column label="编码" prop="endcode" min-width="80" align="center" show-overflow-tooltip/>
      <el-table-column label="药品名称" prop="name" min-width="150" show-overflow-tooltip/>
      <el-table-column label="规格" prop="spec" min-width="80" show-overflow-tooltip/>
      <el-table-column label="单位" prop="unit" min-width="80" align="center" show-overflow-tooltip />
      <el-table-column label="处方单位" prop="prescribeUnit" min-width="100" show-overflow-tooltip/>
      <el-table-column label="医保国家编码" prop="nactionInsurCode" min-width="120" show-overflow-tooltip/>
      <el-table-column label="数量" prop="qty" min-width="80" align="center" show-overflow-tooltip/>
      <el-table-column label="单价" prop="price" min-width="80" align="center" show-overflow-tooltip/>
    </el-table>
    <el-pagination
        class="select-medicine-basic_pagination"
        v-model:current-page="current"
        v-model:page-size="size"
        :page-sizes="[10, 20, 50, 500]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
</template>

<style scoped lang="scss">
.select-medicine-basic {

  &_pagination{
    margin-top: 10px;
  }
}
</style>